package com.example.zdxk.Decoder;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.example.zdxk.entity.*;
import com.example.zdxk.service.*;
import com.example.zdxk.util.*;
import org.apache.commons.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.xml.bind.DatatypeConverter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;

@Component
public class NewsDecoder {
    @Autowired
    private TermService termService;
    @Autowired
    private LocationService locationService;
    @Autowired
    private PointService pointService;              //service利用接口注入
    @Autowired
    private RealtimeService realtimeService;
    @Autowired
    private sys_correctionuserService sys_correctionuserService;

    static private NewsDecoder newsDecoder;

    private byte[] responseBytes = {0x00};
    private Message message = new Message();                      //接收消息的数据结构
    private Message response = new Message();                   //应答消息的数据结构
    private String Imei;                                        //保存Imei

    public String getImei() { return Imei; }


    @PostConstruct
    public void init(){
        newsDecoder = this;
    }

    public byte[] getResponse() {
        return responseBytes;
    }

    /**
     * 解析消息
     * @param resultByte    接收来自终端的消息数组
     */
    public void decode(byte[] resultByte) throws ParseException {

        message.setSync(Arrays.copyOfRange(resultByte, 0, 3));              //将接收的消息封装
        message.setMsg_id(Arrays.copyOfRange(resultByte, 3, 5));
        message.setMes_body_pro(resultByte[5]);
        message.setImei(Arrays.copyOfRange(resultByte, 6, 14));         //8个字节，16位16进制字符,每两位反过来，最后一位0去掉  5368880000005108
        message.setVersion_num(resultByte[14]);
        message.setContent(Arrays.copyOfRange(resultByte, 15, resultByte.length-4));
        message.setMsg_body_termin(resultByte[resultByte.length-4]);
        message.setCheck(resultByte[resultByte.length-3]);
        message.setMsg_termin(Arrays.copyOfRange(resultByte, resultByte.length-2, resultByte.length));

        response.setSync(message.getSync());
        response.setMes_body_pro(message.getMes_body_pro());
        response.setImei(message.getImei());
        response.setVersion_num(message.getVersion_num());
        response.setMsg_body_termin(message.getMsg_body_termin());
        response.setMsg_termin(message.getMsg_termin());

        //Imei = DatatypeConverter.printHexBinary(message.getImei());             //头部中的Imei需要化为16进制字符串形式
        Imei = toImei(DatatypeConverter.printHexBinary(message.getImei()));
        System.out.println("头部中的imei："+Imei);
        String id_s = DatatypeConverter.printHexBinary(message.getMsg_id());             //消息ID
        //---------------根据ID选择相应回复----------


        if("0100".equals(id_s)){                             //终端消息ID 0001 接收消息为 终端通用应答
            temin_Universal_Resp();
            System.out.println(("接收到终端通用应答！"));
        }else if("0600".equals(id_s)){
            termin_Register();
            System.out.println("接收到终端注册消息！");
        }else if("0700".equals(id_s)){                      //终端消息ID 0007 终端注销
            termin_Logout();
            System.out.println("接收到终端注销消息！");
        }else if("1100".equals(id_s)){                      //终端消息ID 0011 终端向平台请求登录消息
            termin_To_Plat_Login();
            System.out.println("接收到终端向平台请求登录消息！");
        }else if("1200".equals(id_s)){                      //终端消息ID 0012 终端向平台查询服务器时间
            termin_Query_Time();
            System.out.println("终端向平台查询服务器时间!");
        }else if("1600".equals(id_s)){                      //终端消息ID 0016 查询终端参数应答
            query_Termin_Para_Resp();
            System.out.println("收到查询终端参数应答！");
        }else if("1700".equals(id_s)){                      //终端消息ID 0017 位置、状态及报警事件单次汇报
            position_Status_Report();
            System.out.println("收到位置、状态及报警事件单次汇报");
        }else if("2500".equals(id_s)){
            history_position_Status_Report();
            System.out.println("收到历史位置信息");
        }else if("2800".equals(id_s)){                      //指纹注册
            fm_Register();
            System.out.println("收到指纹注册！");
        }else if("3000".equals(id_s)){                      //终端向新IP端口请求连接
            ip_Query_Connect();
            System.out.println("收到终端向新IP端口请求连接！");
        }
    }


    /**
     *  消息ID 0030 终端向新IP端口请求连接
     */
    public void ip_Query_Connect(){
        //------------回复--------------
        String result = "00";                                     //结果
        byte[] id ={(byte)0x30, (byte)0x80};

        response.setContent(FormatUtil.hexStringToBytes(result));
        response.setMsg_id(id);
        responseBytes = response.toData();
    }

    /**
     * 终端消息ID 0028 指纹注册   给设备返回成功的信息，让设备可进行下一步
     */
    public void fm_Register(){
        String result = null;
        String imei = new String(Arrays.copyOfRange(message.getContent(),0,15));    //IMEI
        Term term = newsDecoder.termService.getTerminfoByImei(imei);



        if(term != null){                           //终端已注册
            sys_correctionuser sys_correctionuser = newsDecoder.sys_correctionuserService.selectSys_correctionuserByImei(Long.parseLong(imei));
            String flag = sys_correctionuser.getDelFlag();
            if("2".equals(flag)){                   //状态为待绑定2，则设为已绑定0
                sys_correctionuser.setDelFlag("0");
                newsDecoder.sys_correctionuserService.updataDelFlag(sys_correctionuser);
                result = "00";
            }else{                                  //不是待绑定，则绑定失败
                result = "01";
//                result = "00";
            }

        }else{                                         //终端未注册
            result = "01";
//           result = "00";
        }

        //------------回复--------------
        String num = "0000";                                      //流水号
        String resp_id = "2800";                                  //应答ID
        byte[] id ={(byte)0x28, (byte)0x80};

        response.setContent(FormatUtil.hexStringToBytes(num + resp_id + result));
        response.setMsg_id(id);
        responseBytes = response.toData();

    }

    /**
     * 终端消息ID 0006 接收终端注册消息
     */
    public void termin_Register(){
        String imei = new String(Arrays.copyOfRange(message.getContent(),0,15));    //消息体中的imei化为字节所代表的字符形式   358688000000158
        byte permission = message.getContent()[15];                               //权限
        Term term1 = newsDecoder.termService.getTerminfoByImei(Imei);
        if(term1 == null){        //为空就注册
            Term term = new Term();
            term.setterm_imei(imei);
            term.setregister_time(DateUtils.getTime());
            newsDecoder.termService.add(term);
        }else{
            term1.setTerm_logout(0);                    //取消终端注销
            newsDecoder.termService.update(term1);
        }

        //------------回复--------------
        String num = "0000";                                      //流水号
        String resp_id = "0600";                                  //应答ID
        String result = "00";                                     //结果

        byte[] id ={(byte)0x06, (byte)0x80};

        response.setContent(FormatUtil.hexStringToBytes(num + resp_id + result));
        response.setMsg_id(id);
        responseBytes = response.toData();
    }

    /**
     * 终端消息ID 0007 接收终端注销消息
     */
    public void termin_Logout(){
        String imei = new String(Arrays.copyOfRange(message.getContent(),0,15));
        Term term = newsDecoder.termService.getTerminfoByImei(Imei);
        term.setTerm_logout(1);                         //标记终端注销位
        newsDecoder.termService.update(term);


        byte[] num = {(byte)0x00, (byte)0x00};
        byte[] resp_id = message.getMsg_id();
        byte result = (byte)0x00;
        plat_Universal_Resp(num, resp_id, result);          //平台通用应答

    }

    /**
     * 消息ID 8001 发送平台通用应答
     */
    public void plat_Universal_Resp(byte[] num, byte[] resp_id, byte result){
        byte[] id = {(byte)0x01, (byte)0x80};
        String str_num = DatatypeConverter.printHexBinary(num);                     //流水号
        String str_resp_id = DatatypeConverter.printHexBinary(resp_id);            //终端消息的ID
        String str_result = FormatUtil.byteToHexStr(result);                       //结果

        response.setContent(FormatUtil.hexStringToBytes(str_num + str_resp_id + str_result));
        response.setMsg_id(id);
        responseBytes = response.toData();
    }

    /**
     *  终端消息ID 0017 位置、状态及报警事件单次汇报
     */
    public void position_Status_Report() throws ParseException {

        byte[] imei = Arrays.copyOfRange(message.getContent(), 0, 15);
        byte[] time = Arrays.copyOfRange(message.getContent(), 15, 21);
        byte type = message.getContent()[21];                                                 //定位方式
        byte[][] lbs_Data = new byte[3][];
        lbs_Data[0] = Arrays.copyOfRange(message.getContent(), 22, 33);         //基站1                16进制字符串，后面要换成10进制
        lbs_Data[1] = Arrays.copyOfRange(message.getContent(),33,44);         //基站2
        lbs_Data[2] = Arrays.copyOfRange(message.getContent(),44,55);         //基站3
        byte[] gps_Data = Arrays.copyOfRange(message.getContent(),55,73);          //卫星定位数据
        byte[] wifi_Data = Arrays.copyOfRange(message.getContent(),73,157);             //wifi数据
        byte batvalue = message.getContent()[message.getContent().length - 2];
        byte alarm = message.getContent()[message.getContent().length - 1];

        System.out.println("imei: " + new String(imei));
        System.out.println("time: " + DatatypeConverter.printHexBinary(time));      //16进制字符串       用这个，然后时间后面应该是硬件问题
        //System.out.println("time: " + new String(time));                            //直接转为字符串
        System.out.println("type: " + type);
        System.out.println("batvalue: " + batvalue);
        System.out.println("lbs1_data: " + DatatypeConverter.printHexBinary(lbs_Data[0]));
        System.out.println("lbs2_data: " + DatatypeConverter.printHexBinary(lbs_Data[1]));
        System.out.println("lbs3_data: " + DatatypeConverter.printHexBinary(lbs_Data[2]));
        System.out.println("gps_data: " + DatatypeConverter.printHexBinary(gps_Data));
        System.out.println("wifi_data: " + DatatypeConverter.printHexBinary(wifi_Data));

        //定位类型
        int d_lbs_flag = 0x08&type;
        int g_lbs_flag = 0x04&type;
        int gps_flag = 0x01&type;
        int wifi_flag = 0x02&type;

        String gps_location_lat = null;
        String gps_location_lng = null;
        String gps_location_name = null;
        String dlbs_location_lat = null;
        String dlbs_location_lng = null;
        String dlbs_location_name = null;
        String glbs_location_lat = null;
        String glbs_location_lng = null;
        String glbs_location_name = null;
        String wifi_location_lat = null;
        String wifi_location_lng = null;
        String wifi_location_name = null;


        //--------------------单精度基站------------
        if(d_lbs_flag==8){
            String bts = "";
            String mcc="", mnc ="",lac="", ce="", signal="";

            mcc = Integer.parseInt(FormatUtil.reverse(Arrays.copyOfRange(lbs_Data[0],0,2)), 16) + "";
            mnc = Integer.parseInt(FormatUtil.reverse(Arrays.copyOfRange(lbs_Data[0],2,4)), 16) + "";
            lac = Integer.parseInt(FormatUtil.reverse(Arrays.copyOfRange(lbs_Data[0],4,6)), 16) + "";
            ce = Integer.parseInt(FormatUtil.reverse(Arrays.copyOfRange(lbs_Data[0],6,10)), 16) + "";

            JSONObject jsonObject = LbsAPI.getLocJSON(mcc,mnc,lac,ce);
            if(jsonObject.getString("errcode").equals("0")){
                dlbs_location_lat = jsonObject.getString("lat");
                dlbs_location_lng= jsonObject.getString("lon");
                //location_name = jsonObject.getString("address");
                dlbs_location_name = BaiduAPI.getLocName(dlbs_location_lat, dlbs_location_lng);
            }
            System.out.println("dlbs_lat: "+dlbs_location_lat);
            System.out.println("dlbs_name:" +dlbs_location_name);
        }



        //--------------------高精度基站------------
        if(g_lbs_flag==4){
            String bts = "";
            String nearbts = "";
            String mcc="", mnc ="",lac="", ce="", signal="";
            for(int i=0; i<3; i++){
                mcc = Integer.parseInt(FormatUtil.reverse(Arrays.copyOfRange(lbs_Data[i],0,2)), 16) + "";
                mnc = Integer.parseInt(FormatUtil.reverse(Arrays.copyOfRange(lbs_Data[i],2,4)), 16) + "";
                lac = Integer.parseInt(FormatUtil.reverse(Arrays.copyOfRange(lbs_Data[i],4,6)), 16) + "";
                ce = Integer.parseInt(FormatUtil.reverse(Arrays.copyOfRange(lbs_Data[i],6,10)), 16) + "";
                signal = Integer.parseInt(FormatUtil.reverse(Arrays.copyOfRange(lbs_Data[i],10,11)), 16) + "";
                if(i==0){               //bts
                    bts = mcc + "," + mnc +","+ lac +","+ ce +","+ signal;
                }else if(i==1){
                    nearbts = mcc + "," + mnc +","+ lac +","+ ce +","+ signal;
                }else{
                    nearbts = nearbts + "|" + mcc + "," + mnc +","+ lac +","+ ce +","+ signal;
                }
            }

            JSONObject jsonObject = GaodeAPI.getLocByLBS(Imei, bts, nearbts);
            if(!jsonObject.getJSONObject("result").getString("type").equals("0")){
                String[] data_arrr = jsonObject.getJSONObject("result").getString("location").split(",");
                glbs_location_lat = data_arrr[1];
                glbs_location_lng = data_arrr[0];
                glbs_location_name = jsonObject.getJSONObject("result").getString("desc");
            }
            System.out.println("glbs_lat: "+glbs_location_lat);
            System.out.println("glbs_name:" +glbs_location_name);

        }

        //---------------------wifi定位--------------
        if(wifi_flag == 2){
            StringBuffer wifi_Data_bf = new StringBuffer(new String(wifi_Data));
         //   System.out.println("开始前; "+wifi_Data_bf);
            for(int i=wifi_Data_bf.length()-1; i>0; i--){                           //把每组wifi数据用#隔开   最后一个位置不用插
                if(i%14 == 0)wifi_Data_bf.insert(i,"#");                    //不能用“|”,在正则中有特殊含义
            }
            System.out.println("结束后: "+wifi_Data_bf);

            String tmp1 = wifi_Data_bf.toString();
            String[] wifi_arr = tmp1.split("#");
            String macs = "";
            for(int i=0; i<wifi_arr.length; i++){
                //不能用空格去判断呜呜呜,\u0000与空格，null,""都不相等   wifimac 为空，则跳出循环
                if(wifi_arr[i].equals("\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000")) break;
               // System.out.println("\u0000".equals(" "));                     //false
                char[] tmp = wifi_arr[i].toCharArray();
                if(!FormatUtil.isInteger(String.valueOf(tmp[12])) || !FormatUtil.isInteger(String.valueOf(tmp[13]))) continue;              //  00:33:00:b8:29:00,-*    信号值不是数字

                String mmac = "";
                for(int j=0; j<tmp.length; j=j+2){
                    if(j < tmp.length-4)  mmac = mmac + tmp[j] + tmp[j+1] + ":";
                    else if(j == tmp.length-4) mmac = mmac + tmp[j] + tmp[j+1];
                    else mmac = mmac + ",-" + tmp[j] + tmp[j+1];
                }
                System.out.println("mmac: "+mmac);
                if(i == 0) macs = mmac + ",TPLink";
                else macs = macs +  "|" + mmac + ",TPLink";
            }
            System.out.println("macs: "+macs);

            JSONObject jsonObject = GaodeAPI.getLocByWifi(Imei, macs);
            if(!jsonObject.getJSONObject("result").getString("type").equals("0")){
                String[] data_arrr = jsonObject.getJSONObject("result").getString("location").split(",");
                wifi_location_lat = data_arrr[1];
                wifi_location_lng = data_arrr[0];
                wifi_location_name = jsonObject.getJSONObject("result").getString("desc");
                //type = 8;
            }
        System.out.println("wifi_lat: "+wifi_location_lat);
        System.out.println("wifi_name:" +wifi_location_name);
        }


        //-------------------------卫星定位----------
        if(gps_flag == 1){
            String lat_str = FormatUtil.reverse(Arrays.copyOfRange(gps_Data,0,8));          //字节的十六进制形式
            char type_Lat = (char)gps_Data[8];                                                              //十进制化为对应字符  强制类型转化
            String lng_str = FormatUtil.reverse(Arrays.copyOfRange(gps_Data,9,17));
            char type_Lng = (char)gps_Data[17];

            byte[] lat_arr = FormatUtil.hexStringToBytes(lat_str);                              //字节十六进制化为字节数组
            double lat_db =  FormatUtil.getDouble(lat_arr, 0);                          //字节数组化为double      经纬度格式：dd.ddddd
            byte[] lng_arr = FormatUtil.hexStringToBytes(lng_str);
            double lng_db =  FormatUtil.getDouble(lng_arr, 0);

//            System.out.println("----------------");
//            System.out.println("gps_lat: "+lat_db);
//            System.out.println("gps_lng: "+lng_db);
//            System.out.println("gps_lat_type: "+type_Lat);

            // 地址解析
            double[] bd = GPSUtil.gps84_To_bd09(lat_db, lng_db);                                     //谷歌坐标系化为百度坐标系
            gps_location_name = BaiduAPI.getLocName(String.valueOf(bd[0]),String.valueOf(bd[1]));
            double[] gcj02 = GPSUtil.gps84_To_Gcj02(lat_db, lng_db);                                   //存火星坐标系
            gps_location_lat = String.valueOf(gcj02[0]);
            gps_location_lng = String.valueOf(gcj02[1]);


            System.out.println("gps_lat: "+gps_location_lat);
            System.out.println("gps_lng: "+gps_location_lng);
            System.out.println("gps_name:" +gps_location_name);
        }

        Term term = newsDecoder.termService.getTerminfoByImei(Imei);
        Location location = new Location();
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyMMddHHmmss");
        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        location.setterm_imei(Imei);
        location.setbatvalue(batvalue);
        term.setbatvalue((int)batvalue);

        String location_time = DatatypeConverter.printHexBinary(time);
        Date parse = sdf1.parse(location_time);                           //标准化
        location_time = sdf2.format(parse);
        System.out.println("time: "+location_time);
        location.setlocation_time(location_time);       //location_time
        term.setlocation_time(location_time);


//        Point point = new Point();                                                        //在实时数据库中创建Point点
//        point.setRT(4);
//        point.setGN("W3.LOCATION." + Imei + "_LNG");
//        newsDecoder.pointService.insert(point);                                         //插入经度Point点
//        point.setGN("W3.LOCATION." + Imei + "_LAT");                                      //插入纬度Point点
//        newsDecoder.pointService.insert(point);
//        Realtime realtime = new Realtime();
        if(gps_location_name!=null && gps_Data[8]!=0 && gps_location_name!=""){
            location.setlocation_lat(gps_location_lat);
            location.setlocation_lng(gps_location_lng);
            location.setlocation_name(gps_location_name);
            location.setLocation_type(1);
            newsDecoder.locationService.add(location);                    //在mysql中插入经纬度
            term.setlocation_lat(gps_location_lat);
            term.setlocation_lng(gps_location_lng);
            term.setlocation_name(gps_location_name);
            term.setlocation_type(1);
            newsDecoder.termService.update(term);

//            realtime.setGN("W3.LOCATION." + Imei + "_LNG");
//            realtime.setAV(Double.valueOf(gps_location_lng));                      //------当s_lng为null的时候有空指针异常
//            newsDecoder.realtimeService.insert(realtime);
//            realtime.setGN("W3.LOCATION." + Imei + "_LAT");
//            realtime.setAV(Double.valueOf(gps_location_lat));
//            newsDecoder.realtimeService.insert(realtime);                 //在实时数据库中插入经纬度
        }else if(wifi_location_name != null){
            location.setlocation_lat(wifi_location_lat);
            location.setlocation_lng(wifi_location_lng);
            location.setlocation_name(wifi_location_name);
            location.setLocation_type(2);
            newsDecoder.locationService.add(location);                    //在mysql中插入经纬度
            term.setlocation_lat(wifi_location_lat);
            term.setlocation_lng(wifi_location_lng);
            term.setlocation_name(wifi_location_name);
            term.setlocation_type(2);
            newsDecoder.termService.update(term);

//            realtime.setGN("W3.LOCATION." + Imei + "_LNG");
//            realtime.setAV(Double.valueOf(wifi_location_lng));                      //------当s_lng为null的时候有空指针异常
//            newsDecoder.realtimeService.insert(realtime);
//            realtime.setGN("W3.LOCATION." + Imei + "_LAT");
//            realtime.setAV(Double.valueOf(wifi_location_lat));
//            newsDecoder.realtimeService.insert(realtime);                 //在实时数据库中插入经纬度
        }else if(glbs_location_name != null){
            location.setlocation_lat(glbs_location_lat);
            location.setlocation_lng(glbs_location_lng);
            location.setlocation_name(glbs_location_name);
            location.setLocation_type(4);
            newsDecoder.locationService.add(location);                    //在mysql中插入经纬度
            term.setlocation_lat(glbs_location_lat);
            term.setlocation_lng(glbs_location_lng);
            term.setlocation_name(glbs_location_name);
            term.setlocation_type(4);
            newsDecoder.termService.update(term);

//            realtime.setGN("W3.LOCATION." + Imei + "_LNG");
//            realtime.setAV(Double.valueOf(glbs_location_lng));                      //------当s_lng为null的时候有空指针异常
//            newsDecoder.realtimeService.insert(realtime);
//            realtime.setGN("W3.LOCATION." + Imei + "_LAT");
//            realtime.setAV(Double.valueOf(glbs_location_lat));
//            newsDecoder.realtimeService.insert(realtime);                 //在实时数据库中插入经纬度
        }else if(dlbs_location_name != null){
            location.setlocation_lat(dlbs_location_lat);
            location.setlocation_lng(dlbs_location_lng);
            location.setlocation_name(dlbs_location_name);
            location.setLocation_type(8);
            newsDecoder.locationService.add(location);                    //在mysql中插入经纬度
            term.setlocation_lat(dlbs_location_lat);
            term.setlocation_lng(dlbs_location_lng);
            term.setlocation_name(dlbs_location_name);
            term.setlocation_type(8);
            newsDecoder.termService.update(term);

//            realtime.setGN("W3.LOCATION." + Imei + "_LNG");
//            realtime.setAV(Double.valueOf(dlbs_location_lng));                      //------当s_lng为null的时候有空指针异常
//            newsDecoder.realtimeService.insert(realtime);
//            realtime.setGN("W3.LOCATION." + Imei + "_LAT");
//            realtime.setAV(Double.valueOf(dlbs_location_lat));
//            newsDecoder.realtimeService.insert(realtime);                 //在实时数据库中插入经纬度
        }


        //-----------------不用平台通用应答，直接返回8017的空消息
        byte[] id = {(byte)0x17, (byte)0x80};
        response.setMsg_id(id);
        //response.setContent("");                  //todata()内容不能为空
        response.setContent(time);
        responseBytes = response.toData();

        //数据共享
        //upload(term);
        UploadUtil.uploadToConverter(term);
    }


    /**
     *  终端消息ID 0025 历史位置信息         定位上传时间晚于数据库上次时间则更新设备表，否则不更新，但是都传给转发器，转发器也用相同的存储逻辑，时间更晚就更新
     */
    public void history_position_Status_Report() throws ParseException {

        byte[] imei = Arrays.copyOfRange(message.getContent(), 0, 15);
        byte[] time = Arrays.copyOfRange(message.getContent(), 15, 21);
        byte type = message.getContent()[21];                                                 //定位方式
        byte[][] lbs_Data = new byte[3][];
        lbs_Data[0] = Arrays.copyOfRange(message.getContent(), 22, 33);         //基站1                16进制字符串，后面要换成10进制
        lbs_Data[1] = Arrays.copyOfRange(message.getContent(),33,44);         //基站2
        lbs_Data[2] = Arrays.copyOfRange(message.getContent(),44,55);         //基站3
        byte[] gps_Data = Arrays.copyOfRange(message.getContent(),55,73);          //卫星定位数据
        byte[] wifi_Data = Arrays.copyOfRange(message.getContent(),73,157);             //wifi数据
        byte batvalue = message.getContent()[message.getContent().length - 2];
        byte alarm = message.getContent()[message.getContent().length - 1];

        System.out.println("imei: " + new String(imei));
        System.out.println("time: " + DatatypeConverter.printHexBinary(time));      //16进制字符串       用这个，然后时间后面应该是硬件问题
        //System.out.println("time: " + new String(time));                            //直接转为字符串
        System.out.println("type: " + type);
        System.out.println("batvalue: " + batvalue);
        System.out.println("lbs1_data: " + DatatypeConverter.printHexBinary(lbs_Data[0]));
        System.out.println("lbs2_data: " + DatatypeConverter.printHexBinary(lbs_Data[1]));
        System.out.println("lbs3_data: " + DatatypeConverter.printHexBinary(lbs_Data[2]));
        System.out.println("gps_data: " + DatatypeConverter.printHexBinary(gps_Data));
        System.out.println("wifi_data: " + DatatypeConverter.printHexBinary(wifi_Data));

        //定位类型
        int d_lbs_flag = 0x08&type;
        int g_lbs_flag = 0x04&type;
        int gps_flag = 0x01&type;
        int wifi_flag = 0x02&type;

        String gps_location_lat = null;
        String gps_location_lng = null;
        String gps_location_name = null;
        String dlbs_location_lat = null;
        String dlbs_location_lng = null;
        String dlbs_location_name = null;
        String glbs_location_lat = null;
        String glbs_location_lng = null;
        String glbs_location_name = null;
        String wifi_location_lat = null;
        String wifi_location_lng = null;
        String wifi_location_name = null;


        //--------------------单精度基站------------
        if(d_lbs_flag==8){
            String bts = "";
            String mcc="", mnc ="",lac="", ce="", signal="";

            mcc = Integer.parseInt(FormatUtil.reverse(Arrays.copyOfRange(lbs_Data[0],0,2)), 16) + "";
            mnc = Integer.parseInt(FormatUtil.reverse(Arrays.copyOfRange(lbs_Data[0],2,4)), 16) + "";
            lac = Integer.parseInt(FormatUtil.reverse(Arrays.copyOfRange(lbs_Data[0],4,6)), 16) + "";
            ce = Integer.parseInt(FormatUtil.reverse(Arrays.copyOfRange(lbs_Data[0],6,10)), 16) + "";

            JSONObject jsonObject = LbsAPI.getLocJSON(mcc,mnc,lac,ce);
            if(jsonObject.getString("errcode").equals("0")){
                dlbs_location_lat = jsonObject.getString("lat");
                dlbs_location_lng= jsonObject.getString("lon");
                //location_name = jsonObject.getString("address");
                dlbs_location_name = BaiduAPI.getLocName(dlbs_location_lat, dlbs_location_lng);
            }
            System.out.println("dlbs_lat: "+dlbs_location_lat);
            System.out.println("dlbs_name:" +dlbs_location_name);
        }



        //--------------------高精度基站------------
        if(g_lbs_flag==4){
            String bts = "";
            String nearbts = "";
            String mcc="", mnc ="",lac="", ce="", signal="";
            for(int i=0; i<3; i++){
                mcc = Integer.parseInt(FormatUtil.reverse(Arrays.copyOfRange(lbs_Data[i],0,2)), 16) + "";
                mnc = Integer.parseInt(FormatUtil.reverse(Arrays.copyOfRange(lbs_Data[i],2,4)), 16) + "";
                lac = Integer.parseInt(FormatUtil.reverse(Arrays.copyOfRange(lbs_Data[i],4,6)), 16) + "";
                ce = Integer.parseInt(FormatUtil.reverse(Arrays.copyOfRange(lbs_Data[i],6,10)), 16) + "";
                signal = Integer.parseInt(FormatUtil.reverse(Arrays.copyOfRange(lbs_Data[i],10,11)), 16) + "";
                if(i==0){               //bts
                    bts = mcc + "," + mnc +","+ lac +","+ ce +","+ signal;
                }else if(i==1){
                    nearbts = mcc + "," + mnc +","+ lac +","+ ce +","+ signal;
                }else{
                    nearbts = nearbts + "|" + mcc + "," + mnc +","+ lac +","+ ce +","+ signal;
                }
            }

            JSONObject jsonObject = GaodeAPI.getLocByLBS(Imei, bts, nearbts);
            if(!jsonObject.getJSONObject("result").getString("type").equals("0")){
                String[] data_arrr = jsonObject.getJSONObject("result").getString("location").split(",");
                glbs_location_lat = data_arrr[1];
                glbs_location_lng = data_arrr[0];
                glbs_location_name = jsonObject.getJSONObject("result").getString("desc");
            }
            System.out.println("glbs_lat: "+glbs_location_lat);
            System.out.println("glbs_name:" +glbs_location_name);

        }

        //---------------------wifi定位--------------
        if(wifi_flag == 2){
            StringBuffer wifi_Data_bf = new StringBuffer(new String(wifi_Data));
            //   System.out.println("开始前; "+wifi_Data_bf);
            for(int i=wifi_Data_bf.length()-1; i>0; i--){                           //把每组wifi数据用#隔开   最后一个位置不用插
                if(i%14 == 0)wifi_Data_bf.insert(i,"#");                    //不能用“|”,在正则中有特殊含义
            }
            System.out.println("结束后: "+wifi_Data_bf);

            String tmp1 = wifi_Data_bf.toString();
            String[] wifi_arr = tmp1.split("#");
            String macs = "";
            for(int i=0; i<wifi_arr.length; i++){
                //不能用空格去判断呜呜呜,\u0000与空格，null,""都不相等   wifimac 为空，则跳出循环
                if(wifi_arr[i].equals("\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000")) break;
                // System.out.println("\u0000".equals(" "));                     //false
                char[] tmp = wifi_arr[i].toCharArray();
                if(!FormatUtil.isInteger(String.valueOf(tmp[12])) || !FormatUtil.isInteger(String.valueOf(tmp[13]))) continue;              //  00:33:00:b8:29:00,-*    信号值不是数字

                String mmac = "";
                for(int j=0; j<tmp.length; j=j+2){
                    if(j < tmp.length-4)  mmac = mmac + tmp[j] + tmp[j+1] + ":";
                    else if(j == tmp.length-4) mmac = mmac + tmp[j] + tmp[j+1];
                    else mmac = mmac + ",-" + tmp[j] + tmp[j+1];
                }
                System.out.println("mmac: "+mmac);
                if(i == 0) macs = mmac + ",TPLink";
                else macs = macs +  "|" + mmac + ",TPLink";
            }
            System.out.println("macs: "+macs);

            JSONObject jsonObject = GaodeAPI.getLocByWifi(Imei, macs);
            if(!jsonObject.getJSONObject("result").getString("type").equals("0")){
                String[] data_arrr = jsonObject.getJSONObject("result").getString("location").split(",");
                wifi_location_lat = data_arrr[1];
                wifi_location_lng = data_arrr[0];
                wifi_location_name = jsonObject.getJSONObject("result").getString("desc");
                //type = 8;
            }
            System.out.println("wifi_lat: "+wifi_location_lat);
            System.out.println("wifi_name:" +wifi_location_name);
        }


        //-------------------------卫星定位----------
        if(gps_flag == 1){
            String lat_str = FormatUtil.reverse(Arrays.copyOfRange(gps_Data,0,8));          //字节的十六进制形式
            char type_Lat = (char)gps_Data[8];                                                              //十进制化为对应字符  强制类型转化
            String lng_str = FormatUtil.reverse(Arrays.copyOfRange(gps_Data,9,17));
            char type_Lng = (char)gps_Data[17];

            byte[] lat_arr = FormatUtil.hexStringToBytes(lat_str);                              //字节十六进制化为字节数组
            double lat_db =  FormatUtil.getDouble(lat_arr, 0);                          //字节数组化为double      经纬度格式：dd.ddddd
            byte[] lng_arr = FormatUtil.hexStringToBytes(lng_str);
            double lng_db =  FormatUtil.getDouble(lng_arr, 0);

//            System.out.println("----------------");
//            System.out.println("gps_lat: "+lat_db);
//            System.out.println("gps_lng: "+lng_db);
//            System.out.println("gps_lat_type: "+type_Lat);


            // 地址解析
            double[] bd = GPSUtil.gps84_To_bd09(lat_db, lng_db);                                     //谷歌坐标系化为百度坐标系
            gps_location_name = BaiduAPI.getLocName(String.valueOf(bd[0]),String.valueOf(bd[1]));
            double[] gcj02 = GPSUtil.gps84_To_Gcj02(lat_db, lng_db);                                   //存火星坐标系
            gps_location_lat = String.valueOf(gcj02[0]);
            gps_location_lng = String.valueOf(gcj02[1]);



            System.out.println("gps_lat: "+gps_location_lat);
            System.out.println("gps_lng: "+gps_location_lng);
            System.out.println("gps_name:" +gps_location_name);
        }

        Term term = newsDecoder.termService.getTerminfoByImei(Imei);
        Location location = new Location();
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyMMddHHmmss");
        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        int flag = 0;                                           //是否更新设备表 0：否， 1：是

        String location_time = DatatypeConverter.printHexBinary(time);          //上传时间
        Date now = sdf1.parse(location_time);                           //标准化
        Date last = sdf2.parse(term.getlocation_time());                        //上次定位时间
        if(now.before(last)) flag = 0;
        else flag = 1;

        location_time = sdf2.format(now);
        System.out.println("time: "+location_time);
        location.setlocation_time(location_time);       //location_time
        term.setlocation_time(location_time);

        location.setterm_imei(Imei);
        location.setbatvalue(batvalue);
        term.setbatvalue((int)batvalue);

//        Point point = new Point();                                                        //在实时数据库中创建Point点
//        point.setRT(4);
//        point.setGN("W3.LOCATION." + Imei + "_LNG");
//        newsDecoder.pointService.insert(point);                                         //插入经度Point点
//        point.setGN("W3.LOCATION." + Imei + "_LAT");                                      //插入纬度Point点
//        newsDecoder.pointService.insert(point);
//        Realtime realtime = new Realtime();
        if(gps_location_name!=null && gps_Data[8]!=0 && gps_location_name!=""){
            term.setlocation_lat(gps_location_lat);
            term.setlocation_lng(gps_location_lng);
            term.setlocation_name(gps_location_name);
            term.setlocation_type(1);
            if(flag == 1) newsDecoder.termService.update(term);                 //定位时间晚于上次时间，更新设备表
            location.setlocation_lat(gps_location_lat);
            location.setlocation_lng(gps_location_lng);
            location.setlocation_name(gps_location_name);
            location.setLocation_type(1);
            newsDecoder.locationService.add(location);                    //在mysql中插入经纬度

//            realtime.setGN("W3.LOCATION." + Imei + "_LNG");
//            realtime.setAV(Double.valueOf(gps_location_lng));                      //------当s_lng为null的时候有空指针异常
//            newsDecoder.realtimeService.insert(realtime);
//            realtime.setGN("W3.LOCATION." + Imei + "_LAT");
//            realtime.setAV(Double.valueOf(gps_location_lat));
//            newsDecoder.realtimeService.insert(realtime);                 //在实时数据库中插入经纬度
        }else if(wifi_location_name != null){
            term.setlocation_lat(wifi_location_lat);
            term.setlocation_lng(wifi_location_lng);
            term.setlocation_name(wifi_location_name);
            term.setlocation_type(2);
            if(flag == 1) newsDecoder.termService.update(term);
            location.setlocation_lat(wifi_location_lat);
            location.setlocation_lng(wifi_location_lng);
            location.setlocation_name(wifi_location_name);
            location.setLocation_type(2);
            newsDecoder.locationService.add(location);                    //在mysql中插入经纬度

//            realtime.setGN("W3.LOCATION." + Imei + "_LNG");
//            realtime.setAV(Double.valueOf(wifi_location_lng));                      //------当s_lng为null的时候有空指针异常
//            newsDecoder.realtimeService.insert(realtime);
//            realtime.setGN("W3.LOCATION." + Imei + "_LAT");
//            realtime.setAV(Double.valueOf(wifi_location_lat));
//            newsDecoder.realtimeService.insert(realtime);                 //在实时数据库中插入经纬度
        }else if(glbs_location_name != null){
            term.setlocation_lat(glbs_location_lat);
            term.setlocation_lng(glbs_location_lng);
            term.setlocation_name(glbs_location_name);
            term.setlocation_type(4);
            if(flag == 1) newsDecoder.termService.update(term);
            location.setlocation_lat(glbs_location_lat);
            location.setlocation_lng(glbs_location_lng);
            location.setlocation_name(glbs_location_name);
            location.setLocation_type(4);
            newsDecoder.locationService.add(location);                    //在mysql中插入经纬度

//            realtime.setGN("W3.LOCATION." + Imei + "_LNG");
//            realtime.setAV(Double.valueOf(glbs_location_lng));                      //------当s_lng为null的时候有空指针异常
//            newsDecoder.realtimeService.insert(realtime);
//            realtime.setGN("W3.LOCATION." + Imei + "_LAT");
//            realtime.setAV(Double.valueOf(glbs_location_lat));
//            newsDecoder.realtimeService.insert(realtime);                 //在实时数据库中插入经纬度
        }else if(dlbs_location_name != null){
            term.setlocation_lat(dlbs_location_lat);
            term.setlocation_lng(dlbs_location_lng);
            term.setlocation_name(dlbs_location_name);
            term.setlocation_type(8);
            if(flag == 1) newsDecoder.termService.update(term);
            location.setlocation_lat(dlbs_location_lat);
            location.setlocation_lng(dlbs_location_lng);
            location.setlocation_name(dlbs_location_name);
            location.setLocation_type(8);
            newsDecoder.locationService.add(location);                    //在mysql中插入经纬度

//            realtime.setGN("W3.LOCATION." + Imei + "_LNG");
//            realtime.setAV(Double.valueOf(dlbs_location_lng));                      //------当s_lng为null的时候有空指针异常
//            newsDecoder.realtimeService.insert(realtime);
//            realtime.setGN("W3.LOCATION." + Imei + "_LAT");
//            realtime.setAV(Double.valueOf(dlbs_location_lat));
//            newsDecoder.realtimeService.insert(realtime);                 //在实时数据库中插入经纬度
        }



        //-----------------不用平台通用应答，直接返回8017的空消息
        byte[] id = {(byte)0x25, (byte)0x80};
        response.setMsg_id(id);
        //response.setContent("");                  //todata()内容不能为空
        response.setContent(time);
        responseBytes = response.toData();

        //数据共享
        //upload(term);
        UploadUtil.uploadToConverter(term);
    }


    /**
     * 终端消息ID 0011 终端向平台请求登录                                这里应该考虑数据库被删的问题，登录的时候也是添加数据库，和注册一样
     */
    public void termin_To_Plat_Login(){
        byte[] imei = Arrays.copyOfRange(message.getContent(),0,15);
        String result = null;                                     //结果
        if(newsDecoder.termService.getTerminfoByImei(Imei) != null){
            result = "00";
        }else result = "01";

        //------------回复--------------
        String num = "0000";                                      //流水号
        String resp_id = "1100";                                  //应答ID
        String time = DateUtils.dateTimeNow("yyMMddHHmmss");
        byte[] id ={(byte)0x11, (byte)0x80};

        response.setContent(FormatUtil.hexStringToBytes(num + resp_id + time + result));
        response.setMsg_id(id);
        responseBytes = response.toData();
    }

    /**
     *  终端消息ID 0001 接收终端通用应答
     *  包括短信号码注销，平台注销，平台向终端要求验证码鉴权，设置终端参数-定位间隔，定位方式，历史位置长度
     *  推送文本信息
     */
    public void temin_Universal_Resp(){
        byte[] num = Arrays.copyOfRange(message.getContent(),0,2);			        //流水号
        byte[] resp_id = Arrays.copyOfRange(message.getContent(),2,4);				//应答ID
        byte result = message.getContent()[4];					                        	//结果

        String s_resp_id = DatatypeConverter.printHexBinary(resp_id);
        if("0380".equals(s_resp_id)){

        }else if("0580".equals(s_resp_id)){

        }else if("1080".equals(s_resp_id)){

        }else if("1380".equals(s_resp_id)){     //设置终端参数-定位间隔
            if((int)result == 0) System.out.println("定位间隔修改成功");
            else System.out.println("定位间隔修改失败");

        }else if("1480".equals(s_resp_id)) {    //设置终端参数-定位方式
            if((int)result == 0) System.out.println("定位方式修改成功");
            else System.out.println("定位方式修改失败");

        }else if("1580".equals(s_resp_id)){     //设置终端参数-历史位置最大长度

        }else if("2080".equals(s_resp_id)){     //推送文本信息

        }else if("2180".equals(s_resp_id)){     //升级包下发

        }


        System.out.println("应答ID："+ resp_id);
    }

    /**
     * 终端消息ID 0016 查询终端参数应答
     */
    public void query_Termin_Para_Resp(){
        byte[] imei = Arrays.copyOfRange(message.getContent(),0,15);
        byte[] position_intv = Arrays.copyOfRange(message.getContent(),15,17);      //定位间隔
        byte position_method = message.getContent()[17];                                      //定位方式
        byte max_len = message.getContent()[18];                                            //历史位置记录表最大长度
        byte provider = message.getContent()[19];                                           //终端通信服务提供商
        byte[] version = Arrays.copyOfRange(message.getContent(),20,30);            //软件版本
        byte[] type = Arrays.copyOfRange(message.getContent(),30,40);               //终端型号
        byte[] provider_id = Arrays.copyOfRange(message.getContent(),40,60);        //制造商ID
    }

    /**
     * 终端消息ID 0012 终端向平台查询服务器时间
     */
    public void termin_Query_Time(){
        byte[] imei = Arrays.copyOfRange(message.getContent(),0,15);

        //------------回复--------------
        String num = "0000";                                      //流水号
        String resp_id = "1200";                                  //应答ID
        String time = DateUtils.dateTimeNow("yyMMddHHmmss");

        byte[] id ={(byte)0x12, (byte)0x80};

        response.setContent(FormatUtil.hexStringToBytes(num + resp_id + time));
        response.setMsg_id(id);
        responseBytes = response.toData();
    }




    /**
     * 将每两位倒置的Imei转为正确形式
     * @param imei
     * @return
     */
    public String toImei(String imei){
        char[] s = imei.toCharArray();
        for(int i=0; i<s.length; i=i+2){
            char tmp = s[i];
            s[i] = s[i+1];
            s[i+1] = tmp;
        }
        char[] t = Arrays.copyOfRange(s,0,15);
        return new String(t);
    }






}
